package com.qf.flash.ui.business;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.constant.Constant;
import com.qf.flash.constant.FlashCodes;
import com.qf.flash.event.ChangeGroupEvent;
import com.qf.flash.event.SetRoleSuccessEvent;
import com.qf.flash.http.response.GameDetailResponse;
import com.qf.flash.http.response.ScriptDetailResponse;
import com.qf.flash.model.CommentBean;
import com.qf.flash.model.ScriptRoleBean;
import com.qf.flash.mvp.contract.BusOrderOptionContract;
import com.qf.flash.mvp.contract.CommentContract;
import com.qf.flash.mvp.contract.GameDetailContract;
import com.qf.flash.mvp.contract.ScriptDetailContract;
import com.qf.flash.mvp.presenter.BusOrderOptionPresenter;
import com.qf.flash.mvp.presenter.CommentPresenter;
import com.qf.flash.mvp.presenter.GameDetailPresenter;
import com.qf.flash.mvp.presenter.ScriptDetailPresenter;
import com.qf.flash.ui.business.adapter.MemberItem;
import com.qf.flash.ui.chat.ChatActivity;
import com.qf.flash.ui.home.BusinessDetailActivity;
import com.qf.flash.ui.home.ChoseBusinessActivity;
import com.qf.flash.ui.home.MemberMsgActivity;
import com.qf.flash.ui.home.RolePagerActivity;
import com.qf.flash.ui.home.adapter.GameCommentView;
import com.qf.flash.ui.home.adapter.GroupMemberItem;
import com.qf.flash.ui.home.adapter.RoleItem;
import com.qf.flash.utils.ImageLoader;
import com.qf.flash.widget.RatingBarView;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.SpannableStringUtil;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.text.Html.FROM_HTML_MODE_COMPACT;

/**
 * 创建日期：2020/3/15 on 13:25
 * 描述:
 * 作者:戴旭东
 */
public class OrderDetailActivity extends BaseActivity implements GameDetailContract.View, CommentContract.View,
        ScriptDetailContract.View, BusOrderOptionContract.View {

    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.tv_situation)
    TextView tvSituation;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_group_name)
    TextView tv_group_name;
    @BindView(R.id.tv_group_no)
    TextView tvGroupNo;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_bus_name)
    TextView tvBusName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.iv_open_close)
    ImageView ivOpenClose;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_introduce)
    TextView tvIntroduce;
    @BindView(R.id.tv_introduce_title)
    TextView tvIntroduceTitle;
    @BindView(R.id.tv_role_title)
    TextView tv_role_title;
    @BindView(R.id.cl_comment)
    ConstraintLayout cl_comment;
    @BindView(R.id.rv_role)
    RecyclerView rvRole;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_members)
    TextView tvMembers;
    @BindView(R.id.rv_members)
    RecyclerView rvMembers;
    @BindView(R.id.rv_comment)
    RecyclerView rv_comment;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.group_business_msg)
    Group groupBusinessMsg;
    @BindView(R.id.tv_empty_place)
    TextView tvEmptyPlace;
    @BindView(R.id.tv_bottom_action)
    TextView tvBottomAction;
    @BindView(R.id.tv_set_title)
    TextView tv_set_title;
    @BindView(R.id.ll_set)
    LinearLayout llSet;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.rbv_star)
    RatingBarView rbvStar;
    @BindView(R.id.tv_total_comment)
    TextView tvTotalComment;
    @BindView(R.id.tv_gon_chat)
    TextView tvGonChat;
    @BindView(R.id.cl_member)
    ConstraintLayout cl_member;
    private RVAdapter<Object> mCommentAdapter;
    private RVAdapter<Object> mMemberAdapter;
    private RVAdapter<ScriptRoleBean> mRoleAdapter;

    private boolean isOpen;   //是否展开
    private GameDetailPresenter mGameDetailPresenter;
    private CommentPresenter mCommentPresenter;
    private ScriptDetailPresenter mScriptDetailPresenter;
    private BusOrderOptionPresenter mBusOrderOptionPresenter;
    private int page = 1;
    private String orderId, playId;
    private GameDetailResponse response;
    private boolean showRecode; //是否显示收款记录


    public static void start(Activity activity, String playId, String orderId) {
        Intent intent = new Intent(activity, OrderDetailActivity.class);
        intent.putExtra("playId", playId);
        intent.putExtra("orderId", orderId);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String playId, String orderId, boolean showRecode) {
        Intent intent = new Intent(activity, OrderDetailActivity.class);
        intent.putExtra("playId", playId);
        intent.putExtra("orderId", orderId);
        intent.putExtra("showRecode", showRecode);
        activity.startActivity(intent);
    }

    @Override
    protected void initInject() {
        mGameDetailPresenter = new GameDetailPresenter();
        mCommentPresenter = new CommentPresenter();
        mScriptDetailPresenter = new ScriptDetailPresenter();
        mBusOrderOptionPresenter = new BusOrderOptionPresenter();
        initPresenters(mGameDetailPresenter, mCommentPresenter, mScriptDetailPresenter, mBusOrderOptionPresenter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initViewAndData() {
        tvTopTitle.setText("组队详情");
        showRecode = getIntent().getBooleanExtra("showRecode", true);
        if (showRecode)
            ViewUtil.setRightIcon(tvTopRight, R.mipmap.nav_icon_record);
        initCommentRv();
        initMemberRv();
        initRvRole();
        initRefresh();
        orderId = getIntent().getStringExtra("orderId");
        playId = getIntent().getStringExtra("playId");
        mGameDetailPresenter.getGameDetail(orderId);

        if (TextUtils.isEmpty(playId)) {
            tvIntroduce.setVisibility(View.GONE);
            tv_role_title.setVisibility(View.GONE);
            rvRole.setVisibility(View.GONE);
            tvIntroduceTitle.setVisibility(View.GONE);
            cl_comment.setVisibility(View.GONE);
            rv_comment.setVisibility(View.GONE);
            ivOpenClose.setVisibility(View.GONE);
            mRefresh.setEnableLoadMore(false);
        } else {
            mCommentPresenter.getCommentData(playId, page);
            mScriptDetailPresenter.getScriptRole(playId);
        }

    }

    private void initRefresh() {
        mRefresh.setEnableRefresh(false);
        mRefresh.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mCommentPresenter.getCommentData(playId, page);
        });
    }

    private void initRvRole() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvRole.setLayoutManager(linearLayoutManager);
        mRoleAdapter = new RVAdapter<>(new RoleItem());
        rvRole.setAdapter(mRoleAdapter);
        mRoleAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                gotoRolePagerActivity(position);
            }
        });
    }

    private void gotoRolePagerActivity(int pos) {
        ArrayList<ScriptRoleBean> roleBeans = (ArrayList<ScriptRoleBean>) mRoleAdapter.getDatas();
        RolePagerActivity.start(this, roleBeans, pos);
    }

    private void initCommentRv() {
        rv_comment.setLayoutManager(new LinearLayoutManager(this));
        mCommentAdapter = new RVAdapter<>(new GameCommentView());
        rv_comment.setAdapter(mCommentAdapter);
    }


    private void initMemberRv() {
        rvMembers.setLayoutManager(new LinearLayoutManager(this));
        if (showRecode)
            mMemberAdapter = new RVAdapter<>(new MemberItem());
        else
            mMemberAdapter = new RVAdapter<>(new GroupMemberItem());
        rvMembers.setAdapter(mMemberAdapter);
        mMemberAdapter.setOnItemClickListener((view, position) -> {
            Object data = mMemberAdapter.getData(position);
            if (data instanceof GameDetailResponse.UsersBean) {
                GameDetailResponse.UsersBean bean = (GameDetailResponse.UsersBean) data;
                MemberMsgActivity.start(OrderDetailActivity.this, bean.getUid(), "");
            }
        });
    }


    @OnClick({R.id.tv_top_back, R.id.ll_top_right, R.id.tv_mvp, R.id.tv_beauty, R.id.tv_wisdom,
            R.id.tv_courage, R.id.iv_open_close, R.id.tv_bottom_action, R.id.cl_member, R.id.tv_gon_chat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.ll_top_right:
                if (response == null || !showRecode)
                    return;
                MoneyRecodeActivity.start(this, response);
                break;
            case R.id.tv_mvp:
                showSetRoleDialog(FlashCodes.SCORE_MVP);
                break;
            case R.id.tv_beauty:
                showSetRoleDialog(FlashCodes.SCORE_BEAUTY);
                break;
            case R.id.tv_wisdom:
                showSetRoleDialog(FlashCodes.SCORE_WISDOM);
                break;
            case R.id.tv_courage:
                showSetRoleDialog(FlashCodes.SCORE_COURAGE);
                break;
            case R.id.iv_open_close:
                onArrowClick();
                break;
            case R.id.tv_gon_chat:
                if (response != null)
                    ChatActivity.goGroupChat(this, Constant.CHATTYPE_GROUP, response.getEmchatId());
                break;
            case R.id.cl_member:
                if (response != null && !TextUtils.isEmpty(response.getShopId()))
                    BusinessDetailActivity.start(this,
                            orderId, response.getShopId(),
                            response.getEmchatId(), false);
                else if (response != null && TextUtils.isEmpty(response.getShopId())
                        && TextUtils.equals(response.getUserId(), UserMgr.getInstance().getLoginUser().getUid())) {
                    ChoseBusinessActivity.start(this, playId, this.response.getPlayType(), response.getId(), response.getEmchatId());
                }
                break;
            case R.id.tv_bottom_action:
                if (isMine()) {
                    //取消接单
                    mBusOrderOptionPresenter.receiveOrRejectOrder(orderId, FlashCodes.ORDER_REJECT);
                } else {
                    //立即接单
                    mBusOrderOptionPresenter.receiveOrRejectOrder(orderId, FlashCodes.ORDER_RECEIVE);
                }
                break;
        }
    }

    private void showSetRoleDialog(int type) {
        if (response != null)
            SetRoleFragment.newInstarnce(orderId, type, response.getUsers())
                    .setSize(278, 336)
                    .show(getSupportFragmentManager());
    }


    private void onArrowClick() {
        if (isOpen) {
            isOpen = false;
            tvIntroduce.setMaxLines(3);
            ivOpenClose.setRotation(0);
        } else {
            isOpen = true;
            tvIntroduce.setMaxLines(Integer.MAX_VALUE);
            ivOpenClose.setRotation(180);
        }
    }


    @Override
    public void setGDetail(GameDetailResponse response) {
        if (response == null)
            return;
        this.response = response;
        tv_group_name.setText(response.getTeamName());
        tvGroupNo.setText(response.getOrderNumber());
        tvNickName.setText(response.getCaptainName());
        tvTime.setText(response.getCreateDate());
        tvType.setText(response.getTypeName());
        tvAddress.setText(response.getShop().getLocation());
        ImageLoader.loadRoundCorners(this, response.getPlayImage(), ivImg, 5);
        String str = response.getPayedNum() + " / " + response.getNeedNum();
        SpannableStringBuilder stringBuilder = SpannableStringUtil.changeTextColor(str, Color.parseColor("#FABE00"), 0, 1);

        tvCount.setText(stringBuilder);
        tvMembers.setText("组队成员(" + response.getUsers().size() + ")");
        mMemberAdapter.setDatas(new ArrayList<>(response.getUsers()));
        tvSituation.setText(response.getOrderTip());
        if (TextUtils.isEmpty(response.getShopId())) {
            groupBusinessMsg.setVisibility(View.GONE);
            tvEmptyPlace.setVisibility(View.VISIBLE);
        } else {
            groupBusinessMsg.setVisibility(View.VISIBLE);
            tvEmptyPlace.setVisibility(View.GONE);
            tvBusName.setText(response.getShop().getName());
            tvName.setText(response.getShop().getName());
            tvLevel.setText("LV." + response.getShop().getLevel());
            ImageLoader.loadCircleHead(this, response.getShop().getPhoto(), ivHead);
        }
        groupBusinessMsg.updatePreLayout(cl_member);

        tvBottomAction.setVisibility(View.VISIBLE);
        if (response.getIsCanShopFun() != 0) {
            tvBottomAction.setVisibility(View.VISIBLE);
        } else {
            tvBottomAction.setVisibility(View.GONE);
        }
        if (!isMine()) {
            tvBottomAction.setText("立即接单");
        } else {
            tvBottomAction.setText("取消接单");
        }

        if (TextUtils.equals(response.getOrderState(), FlashCodes.ORDER_STATE_YWC)) {
            tv_set_title.setVisibility(View.VISIBLE);
            llSet.setVisibility(View.VISIBLE);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvIntroduce.setText(Html.fromHtml(response.getPlayDesc().replace("\n", "<br>"), FROM_HTML_MODE_COMPACT));
        } else {
            tvIntroduce.setText(Html.fromHtml(response.getPlayDesc().replace("\n", "<br>")));
        }

        //剧本评分
        tvScore.setText(response.getPlayScole() + "");
        rbvStar.setStar(Math.round(response.getPlayScole()), false);
        tvTotalComment.setText(response.getPlayCount() + "次评论");
        showChatIcon(response);

    }

    private void showChatIcon(GameDetailResponse gameDetailBean) {
        if (gameDetailBean == null)
            return;
        String uid = UserMgr.getInstance().getLoginUser().getUid();
        if (TextUtils.equals(uid, gameDetailBean.getShopId())) {
            tvGonChat.setVisibility(View.VISIBLE);
            return;
        }
        for (GameDetailResponse.UsersBean user : gameDetailBean.getUsers()) {
            if (TextUtils.equals(uid, user.getUid())) {
                tvGonChat.setVisibility(View.VISIBLE);
                break;
            }
        }

    }


    private boolean isMine() {
        return response.getIsCanShopFun() == 2;
    }

    @Override
    public void setCommentData(List<CommentBean> commentBeans, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, false);
        List<Object> datas = mCommentAdapter.getDatas();
        datas.addAll(new ArrayList<>(commentBeans));
        mCommentAdapter.notifyDataSetChanged();
        if (page >= totalPage)
            mRefresh.setEnableLoadMore(false);
    }

    @Override
    public void setScriptDetail(ScriptDetailResponse response) {
//        if (response == null)
//            return;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            tvIntroduce.setText(Html.fromHtml(response.getContent(), FROM_HTML_MODE_COMPACT));
//        } else {
//            tvIntroduce.setText(Html.fromHtml(response.getContent()));
//        }
//
//        //剧本评分
//        tvScore.setText(response.getResponseScole()+"");
//        rbvStar.setStar(Math.round(response.getResponseScole()),false);
//        tvTotalComment.setText(response.getResponseCount()+"次评论");

    }

    @Override
    public void setScriptRole(List<ScriptRoleBean> roleBeans) {
        mRoleAdapter.setDatas(roleBeans);
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, false);
    }

    @Override
    public void receiveOrRejectOrderSuccess(int optionType) {
        switch (optionType) {
            case FlashCodes.ORDER_RECEIVE:
                tvBottomAction.setText("取消接单");
                tvGonChat.setVisibility(View.VISIBLE);
                break;
            case FlashCodes.ORDER_REJECT:
                tvBottomAction.setText("立即接单");
                tvGonChat.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    @Subscribe
    public void onGroupChangeEvent(ChangeGroupEvent event) {
        mGameDetailPresenter.getGameDetail(orderId);
    }

    @Subscribe
    public void onSetRoleEvent(SetRoleSuccessEvent event) {
        mGameDetailPresenter.getGameDetail(orderId);
    }

    @Override
    public void shopOpCompletedSuccess() {

    }

    @Override
    public void shopOpStartGameSuccess() {

    }

    @Override
    public void shopOpEndGameSuccess() {

    }

    @Override
    public void shopOpMoneySuccess() {

    }
}
